﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ProgNetComponentsDx.Browsers;

namespace BuildHelper.Work.Tools
{
    public partial class ResManControl : UserControl
    {
        public ResManControl()
        {
            InitializeComponent();
        }

        public string Brancz
        {
            get { return lueBrancz.EditValue.AsString(); }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!this.IsDesignMode())
            {
                lueBrancz.EditValue = Setup.Brancze.BranczeTools.ActiveBranch;
                Setup.Brancze.BranczeTools.ActiveBranchChanged += new EventHandler(BranczeTools_ActiveBranchChanged);
            }
        }

        void BranczeTools_ActiveBranchChanged(object sender, EventArgs e)
        {
            lueBrancz.EditValue = Setup.Brancze.BranczeTools.ActiveBranch;
        }

        public string GetGcmResManFile(string brancz)
        {
            DataRow r = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Setup.Brancze, brancz);
            if (r != null)
            {
                string katalog = r["STP_BR_KATALOG"].AsString().TrimEnd('\\');
                string file = katalog + @"\nd_src\gene\apps\gcm\src\gui\GcmResMan\";
                file += "GcmResMan.resx";
                return file;
            }
            return "";
        }

        public string GetDBsResManFile(string brancz)
        {
            DataRow r = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Setup.Brancze, brancz);
            if (r != null)
            {
                string katalog = r["STP_BR_KATALOG"].AsString().TrimEnd('\\');
                string file = katalog + @"\nd_src\gene\apps\gcm\src\gui\GcmResMan\";
                file += "DBsResMan.resx";
                return file;
            }
            return "";
        }

        private void Add(bool dbs)
        {
            string brancz = lueBrancz.EditValue.AsString();
            string text = meResMan.Text;
            if (text.IsNullOrEmpty())
            {
                FindForm().ShowDxInfoDialog("Nie ma nic do dodania.");
                return;
            }
            text = text.TrimStartEnd() + Constants.NewLineLinux + "  ";
            if (brancz.IsNotNull())
            {
                DataRow r = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Setup.Brancze, brancz);
                if (r != null)
                {
                    string file = "";
                    if (dbs)
                        file = GetDBsResManFile(brancz);
                    else
                        file = GetGcmResManFile(brancz);

                    if (System.IO.File.Exists(file))
                    {
                        string content = file.ReadFile();
                        List<string> list = text.GetMatches("<data name=\"([^\"]*)\"");
                        string err = "";
                        List<string> errors = new List<string>();
                        foreach (string s in list)
                        {
                            if (content.IndexOf("name=\"" + s + "\"") != -1)
                            {
                                err = err.AppendLine("Wpis " + s + " już istnieje");
                                errors.Add(s);
                            }
                        }
                        DialogResult dlg = DialogResult.Yes;
                        if (err.IsNotNull())
                        {
                            dlg = this.FindForm().ShowDxYNQuestionDialog(err + "\n" + "Czy chcesz dodać brakujące wpisy?");
                        }
                        if (dlg == DialogResult.Yes)
                        {
                            foreach (string s in errors)
                            {
                                text = text.XReplace("<data name=\"" + s.XEscape() + "\".*?</data>", "", System.Text.RegularExpressions.RegexOptions.Singleline);
                                text = text.TrimStartEnd() + Constants.NewLineLinux + "  ";
                            }
                            if (text.IsNotNull())
                            {
                                int idx = content.LastIndexOf("<data name=");
                                content = content.Insert(idx, text).Trim();
                                content.WriteToFile(file);
                                FormMain.ShowInfoAlert("Wpisy dodane");
                            }
                            else
                            {
                                FindForm().ShowDxInfoDialog("Nic do dodania.");
                            }
                        }
                    }
                    else
                    {
                        FindForm().ShowDxErrorDialog("Brak pliku:\n" + file);
                    }
                }
                else
                {
                    FindForm().ShowDxErrorDialog("Nie można znaleźć brancza.");
                }
            }
            else
            {
                FindForm().ShowDxInfoDialog("Wybierz brancza.");
            }
        }

        private void btnDbs_Click(object sender, EventArgs e)
        {
            Add(true);
        }

        private void btnGcm_Click(object sender, EventArgs e)
        {
            Add(false);
        }

        private void btnCopy_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(meResMan.Text);
        }

        public new string Text
        {
            get
            {
                return meResMan.Text;
            }
            set
            {
                meResMan.Text = value;
            }
        }
        
        public void AppendText(string code, string name)
        {
            meResMan.AppendText(GetResX(code,name));
        }

        private string GetResX(string code, string text)
        {
            string resMan = "  <data name=\"" + code + "\" xml:space=\"preserve\">" + Constants.NewLineLinux +
                            "    <value>" + text + "</value>" + Constants.NewLineLinux +
                            "  </data>";
            return resMan + Constants.NewLineLinux;
        }
    }
}
